<template>
  <bs-dialog :title="editorForm.id? $t('修改标签类别'):$t('添加标签类别')" :visible.sync="editor" size="mini" @closed="doCloseEdit" class="deviceDialog">
    <template slot="main">
      <el-form :model="editorForm" :rules="editorFormRules" ref="editorFormRef" size="small" :show-message="false" :hide-required-asterisk="true" :status-icon="false">
        <input v-model="editorForm.id" type="hidden" />
        <input v-model="editorForm.type" type="hidden" />
        <el-form-item label="" prop="name">
          <el-input v-model="editorForm.name" :placeholder="$t('请输入标签类型名称')" maxlength="20" autocomplete="off" :show-word-limit="false" clearable></el-input>
        </el-form-item>
      </el-form>
    </template>

    <template slot="footer">
      <bs-confirm-button-icon @click.native="doSave"></bs-confirm-button-icon>
      <bs-cancel-button-icon @click.native="doCloseEdit"></bs-cancel-button-icon>
    </template>
  </bs-dialog>
</template>

<script>
import ScreenApi from '@/api/screen'
export default {
  name: 'SetTagTypeDialog',
  data() {
    return {
      editor: false,
      editorForm: {
        ids: 0,
        name: ''
      },
      editorFormRules: {
        name: [
            { required: true, message: '请输入标签类型名称', trigger: 'blur' },
            { pattern: /^[[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '名称类型输入不合法'}
        ]
      }
    }
  },
  created() {
    this.$eventBus.$on('showSetTagTypeDialog', this.show);
  },
  beforeDestroy() {
    this.$eventBus.$off('showSetTagTypeDialog');
  },
  methods: {
    // 显示
    show(data) {
      this.editorForm = data
      this.editor = true
    },
    // 关闭
    doCloseEdit: function () {
      this.$refs.editorFormRef.clearValidate()
      this.editor = false
    },
    // 保存表单
    async doSave() {
      this.$refs.editorFormRef.clearValidate()
      this.$refs.editorFormRef.validate(async valid => {
        if (valid) {
          let res = false
          if(this.editorForm.id && this.editorForm.id > 0) {
            res = await ScreenApi.editTagTypes(this.editorForm)
          } else {
            res = await ScreenApi.addTagTypes(this.editorForm)
          }

          this.editor = false
          this.$emit('refresh')
          this.editorForm.id && this.editorForm.id > 0 ? this.$success('upd') : this.$success('add')

        } else {
          let index = 0
          this.$refs.editorFormRef.fields.forEach(field => {
            if(field.validateMessage) {
              if(index === 0) {
                console.log(field.validateMessage)
                this.$message.error(field.validateMessage)
                this.validateMsg=[]
              }
              index ++
            }
          })
          return
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form {
  padding: 40px 10px 0 15px;
}
::v-deep .el-dialog {
  width: 350px;
  height: 200px;
}
::v-deep .el-select-tree {
    width: 240px;
}
::v-deep .el-dialog__footer {
  border: 0;
}
</style>
